import {
  Tree,
  DataSet,
  TextField,
} from 'choerodon-ui/pro';
import Record from 'choerodon-ui/pro/lib/data-set/Record';
import React, { useMemo } from 'react';
import treeDS from './treeDataSet';

const nodeRenderer = ({ record }: { record?: Record | null | undefined }): React.ReactNode => {
  return record?.get('text');
};

const TreeSearch: React.FC = (): React.ReactElement => {

  const treeDatasSet: DataSet = useMemo(() => new DataSet(treeDS()), []);

  const handleChange = async (value: string, oldValue: string) => {
    if (value !== oldValue) {
     const filterRecord = treeDatasSet.filter((record) => {
        if(record.get('expand')){
          record.set('expand', false);
        }
        return record.get('text').indexOf(value) > -1;
      });
      filterRecord.forEach((item) => {
        let ItemCopy = item;
        while(ItemCopy.parent){
          ItemCopy = ItemCopy.parent;
          if(!ItemCopy.get('expand')){
            ItemCopy.set('expand', true);
          }
        }
      });
    }
  };

  return (
    <>
      <TextField onChange={handleChange} />
      <Tree
        dataSet={treeDatasSet}
        checkable
        renderer={nodeRenderer}
      />
    </>
  );
};

export default TreeSearch;